package com.zodiac.alioth.web.controller;

import com.zodiac.alioth.common.enums.ApiRespCodeEnum;
import com.zodiac.alioth.common.model.vo.ApiResponse;
import com.zodiac.alioth.common.util.FFmpegUtil;
import com.zodiac.alioth.service.biz.media.VideoService;
import com.zodiac.alioth.web.security.LoginContextHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Slf4j
@Controller
public class UploadController {

    @Resource
    private VideoService videoService;

    /**
     * 上传文件，成功返回文件路径名，失败返回报错信息
     *
     * @param file
     * @return
     */
    @RequestMapping(value = "/web/upload", method = RequestMethod.POST)
    @ResponseBody
    public ApiResponse fileUpload(@RequestParam("file") MultipartFile file) {
        try {
            String userId = LoginContextHelper.getLoginUserId() == null ? "sys" : LoginContextHelper.getLoginUserId();
            if (StringUtils.isEmpty(userId)) {
                return ApiResponse.getResult(ApiRespCodeEnum.UNAUTHORIZED);
            }
            String filename = file.getOriginalFilename();
            long fileTime = System.currentTimeMillis();
            String folder = FFmpegUtil.getExtraPath() + "/temp/mao/" + userId + "/" + fileTime;
            filename = folder + "/" + filename;
            File f = new File(folder);

            String newFileName = null;
            if (!f.exists()) {
                boolean mkdirs = f.mkdirs();
                if (mkdirs) {
                    byte[] bytes = file.getBytes();
                    Path path = Paths.get(filename);
                    Files.write(path, bytes);
                    newFileName = videoService.formatConversion(filename, fileTime, file.getOriginalFilename());
                }
            }

            return ApiResponse.getSuccessResult(newFileName);
        } catch (IOException e) {
            log.error("上传图片异常", e);
            return ApiResponse.getFailureResult(9999, "上传图片异常");
        }
    }

    /**
     * @param ossKey   路径名(ossKey)
     * @param response
     * @param request
     */
//    @RequestMapping("/file/download")
//    public void fileDownload(String ossKey, HttpServletResponse response, HttpServletRequest request) {
//        if (StringUtils.isBlank(ossKey)) {
//            log.warn(this.getClass() + " 文件下载错误,ossKey：" + ossKey);
//            return;
//        }
//        String deOssKey = null;
//        try {
//            deOssKey = URLDecoder.decode(ossKey, "UTF-8");
//        } catch (UnsupportedEncodingException e) {
//            log.error(" 文件下载错误, ossKey：" + ossKey, e);
//        }
//        if (StringUtils.isBlank(deOssKey)) {
//            log.warn(this.getClass() + " 文件下载错误, 解码后deOssKey：" + ossKey);
//            return;
//        }
//        try {
//            OutputStream out = response.getOutputStream();
//            response.setContentType("application/x-excel");
//            String userAgent = request.getHeader("User-Agent");
//            // 根据浏览器改变文件名编码
//            String filename = deOssKey.substring(ossKey.lastIndexOf("/") + 1);
//            String finalFileName = getEncodingFileName(userAgent, filename);
//            response.setHeader("Content-Disposition", "attachment; " + finalFileName);
//            InputStream in = ossHelper.get(deOssKey);
//            writeIn2OutputStream(in, out);
//            log.info("finalFileName:" + finalFileName);
//        } catch (IOException e) {
//            log.error(" 文件下载失败, deOssKey：" + deOssKey, e);
//        }
//    }

    /**
     * 输入流写到输出流
     *
     * @param in
     * @param out
     * @throws IOException
     */
    private void writeIn2OutputStream(InputStream in, OutputStream out) throws IOException {
        byte[] temp = new byte[1024];
        int b = 0;
        if (in != null) {
            while ((b = in.read(temp)) != -1) {
                out.write(temp, 0, b);
            }
        }
        if (out != null) {
            out.flush();
        }
    }

    /**
     * 文件名兼容性
     *
     * @param userAgent
     * @param fileName
     * @return
     * @throws IOException
     */
    private String getEncodingFileName(String userAgent, String fileName)
            throws IOException {
        if (StringUtils.isNotBlank(userAgent)
                && StringUtils.isNotBlank(fileName)) {
            String newEncodingFileName = URLEncoder.encode(fileName, "UTF-8");
            String encodingFileName = "filename=\"" + newEncodingFileName + "\"";
            userAgent = userAgent.toLowerCase();
            if (userAgent.contains("msie") || userAgent.contains("chrome")) {
                // IE,Chrome浏览器
                encodingFileName = "filename=\"" + newEncodingFileName + "\"";
            } else if (userAgent.contains("opera") || userAgent.contains("firefox")) {
                // Opera, FireFox浏览器采用filename*
                encodingFileName = "filename*=UTF-8''" + newEncodingFileName;
            } else if (userAgent.contains("version")) {
                // Safari浏览器，只能采用ISO编码的中文输出
                encodingFileName = "filename=\""
                        + new String(fileName.getBytes("UTF-8"), "ISO8859-1")
                        + "\"";
            }
            return encodingFileName;
        }
        return "";
    }
}